<template>
    <div class="page-container">
      <!-- 筛选区卡片 -->
      <div class="filter-card">
        <el-form :inline="true" :model="searchForm" class="filter-form">
          <el-form-item label="类型编码">
            <el-input v-model="searchForm.typeCode" placeholder="请输入类型编码" clearable />
          </el-form-item>
          <el-form-item label="类型名称">
            <el-input v-model="searchForm.typeName" placeholder="请输入类型名称" clearable />
          </el-form-item>
          <el-form-item label="保养维护类型">
            <el-select v-model="searchForm.maintenanceType" placeholder="请选择保养维护类型" clearable style="width: 180px;">
              <el-option label="按使用次数维护" value="按使用次数维护" />
              <el-option label="定期维护" value="定期维护" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="onSearch">查询</el-button>
            <el-button :icon="Refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 操作按钮区 -->
      <div class="operation-area">
        <el-button type="primary" :icon="Plus" @click="onAdd">新增</el-button>
        <el-button type="primary" :icon="Edit" @click="onEdit">修改</el-button>
        <el-button type="danger" :icon="Delete" @click="onDelete">删除</el-button>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          border 
          v-loading="loading"
          @selection-change="handleSelectionChange"
          height="100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="typeCode" label="类型编码" width="150" />
          <el-table-column prop="typeName" label="类型名称" width="150" />
          <el-table-column label="是否编码管理" width="120" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.isCodeManaged == 0" type="primary">是</el-tag>
              <el-tag v-else type="danger">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isMaintenanceType" label="保养维护类型" width="150">
            <template #default="{ row }">
              <span>{{ row.isMaintenanceType || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="maintenanceCycle" label="保养周期" width="120">
            <template #default="{ row }">
              <span>{{ row.maintenanceCycle || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" min-width="120" show-overflow-tooltip />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">修改</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog 
        v-model="dialogVisible" 
        :title="isEdit ? '编辑工装类型' : '添加工装类型'" 
        width="1000px"
        :close-on-click-modal="false"
        destroy-on-close
        class="custom-dialog"
      >
        <div class="dialog-content">
          <el-form 
            ref="formRef" 
            :model="formData" 
            :rules="formRules" 
            label-width="120px"
            class="dialog-form"
          >
            <div class="form-row">
              <el-form-item label="类型编码" prop="typeCode" required>
                <div class="code-input-container">
                  <el-input v-model="formData.typeCode" placeholder="请输入类型编码" :disabled="isEdit || formData.autoGenerate" style="flex: 1;" />
                  <div v-if="!isEdit" class="auto-generate-container">
                    <div class="auto-generate-label">自动生成</div>
                    <el-switch
                      v-model="formData.autoGenerate"
                      class="auto-generate-switch"
                    />
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="类型名称" prop="typeName" required>
                <el-input v-model="formData.typeName" placeholder="请输入类型名称" />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="是否编码管理" prop="isCodeManaged" required>
                <el-radio-group v-model="formData.isCodeManaged">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="保养维护类型" prop="isMaintenanceType">
                <el-select v-model="formData.isMaintenanceType" placeholder="请选择保养维护类型" style="width: 100%;">
                  <el-option label="按使用次数维护" value="按使用次数维护" />
                  <el-option label="定期维护" value="定期维护" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item 
                label="保养周期" 
                prop="maintenanceCycle" 
              >
                <el-input v-model="formData.maintenanceCycle" placeholder="请输入保养周期" />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="备注" prop="remarks">
                <el-input 
                  v-model="formData.remarks" 
                  type="textarea" 
                  :rows="4" 
                  placeholder="请输入备注信息" 
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import http from '@/api/http';
  import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue';
  
  // API基础路径
  const baseApiUrl = '/api/ToolType';
  
  // 加载状态
  const loading = ref(false);
  const submitLoading = ref(false);
  
  // 搜索表单
  const searchForm = reactive({
    typeCode: '',
    typeName: '',
    maintenanceType: ''
  });
  
  // 表格数据
  const tableData = ref([]);
  
  // 分页相关
  const pagination = reactive({
    pageIndex: 1,
    pageSize: 10,
    total: 0
  });
  
  // 选中的行
  const selectedRows = ref([]);
  
  // 新增/编辑弹窗相关
  const dialogVisible = ref(false);
  const isEdit = ref(false);
  const formRef = ref();
  const formData = reactive({
    id: '',
    typeCode: '',
    typeName: '',
    isCodeManaged: 1,
    isMaintenanceType: 0,
    maintenanceCycle: '',
    remarks: '',
    autoGenerate: false
  });
  
  // 表单验证规则
  const formRules = {
    typeCode: [
      { required: true, message: '请输入类型编码', trigger: 'blur' },
      { pattern: /^[A-Z0-9]+$/, message: '类型编码只能包含大写字母和数字', trigger: 'blur' }
    ],
    typeName: [
      { required: true, message: '请输入类型名称', trigger: 'blur' }
    ],
    isCodeManaged: [
      { required: true, message: '请选择是否编码管理', trigger: 'change' }
    ]
  };
  
  // 生命周期钩子
  onMounted(() => {
    // 初始化加载数据
    getTableData();
  });
  
  // 加载表格数据
  const getTableData = async () => {
    try {
      loading.value = true;
  
      // 构建查询参数
      const params = {
        pageIndex: pagination.pageIndex,
        pageSize: pagination.pageSize,
        typeCode: searchForm.typeCode || null,
        typeName: searchForm.typeName || null,
        maintenanceType: searchForm.maintenanceType || null
      };
  
      console.log('查询参数:', params);
  
      // API调用 - 获取工装类型列表
      const response = await http.post(`/api/TypeSetup/GetTypeSetup`, params);
      console.log('API响应数据:', response);
  
      if (response && response.status) {
        // 检查响应数据结构
        if (response.data && Array.isArray(response.data.rows)) {
          tableData.value = response.data.rows;
          pagination.total = response.data.total || 0;
        } else if (Array.isArray(response.rows)) {
          tableData.value = response.rows;
          pagination.total = response.total || 0;
        } else if (Array.isArray(response.data)) {
          tableData.value = response.data;
          pagination.total = response.total || response.data.length || 0;
        } else {
          tableData.value = [];
          pagination.total = 0;
          console.error('未知的响应数据结构:', response);
        }
      } else {
        ElMessage.error(response?.message || '获取数据失败');
        tableData.value = [];
        pagination.total = 0;
      }
    } catch (error) {
      console.error('获取数据出错:', error);
      ElMessage.error('获取数据失败，请稍后再试');
      tableData.value = [];
      pagination.total = 0;
    } finally {
      loading.value = false;
    }
  };
  
  // 搜索
  const onSearch = () => {
    pagination.pageIndex = 1;
    getTableData();
  };
  
  // 重置搜索
  const onReset = () => {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = '';
    });
    pagination.pageIndex = 1;
    getTableData();
  };
  
  // 表格选择变化
  const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
    console.log('选中行数组:', selectedRows.value);
  };
  
  // 分页大小变化
  const handleSizeChange = (val) => {
    pagination.pageSize = val;
    getTableData();
  };
  
  // 当前页变化
  const handleCurrentChange = (val) => {
    pagination.pageIndex = val;
    getTableData();
  };
  
  // 监听自动生成勾选状态
  watch(() => formData.autoGenerate, (newVal) => {
    if (newVal) {
      // 自动生成编号：TC + 年月日时分秒
      const now = new Date();
      const year = now.getFullYear().toString().slice(2);
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      
      formData.typeCode = `TC${year}${month}${day}${hours}${minutes}${seconds}`;
    } else {
      // 关闭自动生成时，清空编号
      formData.typeCode = '';
    }
  });
  
  // 新增
  const onAdd = () => {
    isEdit.value = false;
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields();
    }
    
    // 设置默认值
    formData.id = '';
    formData.typeCode = '';
    formData.typeName = '';
    formData.isCodeManaged = 1;
    formData.isMaintenanceType='';
    formData.maintenanceCycle = '';
    formData.remarks = '';
    formData.autoGenerate = false;
    
    dialogVisible.value = true;
  };
  
  // 获取保养类型文本
  const getMaintenanceTypeText = (type) => {
    if (!type) return '无';
    return type;
  };
  
  // 点击编辑按钮（工具栏）
  const onEdit = () => {
    if (selectedRows.value.length !== 1) {
      ElMessage.warning('请选择一条记录进行修改');
      return;
    }
    
    handleEdit(selectedRows.value[0]);
  };
  
  // 编辑行
  const handleEdit = (row) => {
    isEdit.value = true;
    
    console.log('编辑的行数据:', row);
    
    // 填充表单数据
    formData.id = row.id || 0;
    formData.typeCode = row.typeCode || '';
    formData.typeName = row.typeName || '';
    formData.isCodeManaged = row.isCodeManaged !== undefined ? Number(row.isCodeManaged) : 1;
    formData.isMaintenanceType = row.isMaintenanceType || '';
    formData.maintenanceCycle = row.maintenanceCycle || '';
    formData.remarks = row.remarks || '';
    
    dialogVisible.value = true;
  };
  
  // 点击删除按钮（工具栏）
  const onDelete = async () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请至少选择一条记录');
      return;
    }
    
    const ids = selectedRows.value.map(row => row.id).join(',');
    handleDeleteById(ids, selectedRows.value.length > 1);
  };
  
  // 删除行
  const handleDelete = (row) => {
    handleDeleteById(row.id, false);
  };
  
  // 根据ID删除
  const handleDeleteById = async (ids, isBatch) => {
    try {
      await ElMessageBox.confirm(
        isBatch ? `确认删除选中的 ${selectedRows.value.length} 条记录吗？` : '确认删除此记录吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
      
      loading.value = true;
      
      try {
        // 调用后台删除接口
        const response = await http.post(`/api/TypeSetup/RemTypeSetup?id=${ids}`);
        console.log('删除响应:', response);
        
        if (response && response.status) {
          ElMessage.success('删除成功');
          getTableData(); // 重新加载数据
        } else {
          ElMessage.error(response?.message || '删除失败');
        }
      } catch (apiError) {
        console.error('删除API调用失败:', apiError);
        ElMessage.error('删除失败: ' + (apiError.message || '服务器错误'));
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除操作被取消:', error);
      }
    } finally {
      loading.value = false;
    }
  };
  
  // 提交表单
  const onSubmit = async () => {
    try {
      await formRef.value.validate();
      
      submitLoading.value = true;
      
      // 准备提交的数据
      const submitData = {
        id: formData.id || 0,
        typeCode: formData.typeCode,
        typeName: formData.typeName,
        isCodeManaged: Number(formData.isCodeManaged),
        isMaintenanceType: formData.isMaintenanceType,
        maintenanceCycle: formData.maintenanceCycle,
        remarks: formData.remarks || ''
      };

      console.log('提交的数据:', submitData);
      
      let response;
      try {
        if (isEdit.value) {
          // 编辑模式 - 调用更新接口
          response = await http.post(`/api/TypeSetup/UpdTypeSetup`, submitData);
        } else {
          // 新增模式 - 调用添加接口
          response = await http.post(`/api/TypeSetup/AddTypeSetup`, submitData);
        }
        
        console.log('API响应:', response);
        
        if (response && response.status) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          getTableData(); // 重新加载数据
        } else {
          ElMessage.error(response?.message || (isEdit.value ? '更新失败' : '添加失败'));
        }
      } catch (apiError) {
        console.error('API调用失败:', apiError);
        ElMessage.error('操作失败: ' + (apiError.message || '服务器错误'));
      }
    } catch (error) {
      console.error('表单验证失败:', error);
      ElMessage.error('表单验证失败，请检查输入');
    } finally {
      submitLoading.value = false;
    }
  };
  </script>
  
  <style scoped>
  .page-container {
    padding: 20px;
    width: 100%;
    box-sizing: border-box;
    height: calc(100vh - 40px); /* 减去上下padding */
    display: flex;
    flex-direction: column;
  }
  
  .filter-card {
    background: #f5f7fa;
    padding: 16px 16px 0 16px;
    border-radius: 6px;
    margin-bottom: 10px;
    flex-shrink: 0;
  }
  
  .filter-form {
    margin-bottom: 0;
  }
  
  .operation-area {
    margin: 10px 0;
    display: flex;
    gap: 10px;
    flex-shrink: 0;
  }
  
  /* 表格容器占满剩余空间 */
  .table-container {
    flex: 1;
    overflow: hidden;
    position: relative;
  }
  
  /* 表格样式 */
  :deep(.el-table) {
    height: 100% !important;
  }
  
  /* 分页容器固定在底部 */
  .pagination-container {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
    flex-shrink: 0;
    padding: 5px 0;
  }
  
  /* 弹窗样式 */
  :deep(.custom-dialog .el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  :deep(.custom-dialog .el-dialog__header) {
    background-color: #f5f7fa;
    padding: 15px 20px;
    margin: 0;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.custom-dialog .el-dialog__title) {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
  
  :deep(.custom-dialog .el-dialog__body) {
    padding: 20px;
  }
  
  :deep(.custom-dialog .el-dialog__footer) {
    padding: 10px 20px;
    border-top: 1px solid #e4e7ed;
  }
  
  .dialog-content {
    max-height: 60vh;
    overflow-y: auto;
  }
  
  .dialog-form .el-form-item {
    margin-bottom: 18px;
  }
  
  .form-row {
    display: flex;
    margin-bottom: 0;
    width: 100%;
  }
  
  .form-row .el-form-item {
    flex: 1;
    margin-right: 20px;
  }
  
  .form-row .el-form-item:last-child {
    margin-right: 0;
  }
  
  .code-input-container {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 10px;
  }
  
  .auto-generate-container {
    display: flex;
    align-items: center;
    white-space: nowrap;
    gap: 5px;
  }
  
  .auto-generate-label {
    font-size: 14px;
    color: #606266;
  }
  
  .auto-generate-switch {
    margin-left: 5px;
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
  
  :deep(.el-form-item.is-required .el-form-item__label:before) {
    color: #f56c6c;
  }
  
  .dialog-footer {
    text-align: right;
  }
  </style>